import { isString, isRegExp } from "../is";
import { Recordable } from "../ts";
import { ValueError } from "../exceptions";


declare type filter = {test:string|RegExp,handle:(env:string)=>any}


/**
 * Filter all environment variables starting with VITE.
 * @param envConf 
 * @example
 * ```ts
 * import { defineConfig, loadEnv } from 'vite'
 * import { getViteEnvs } from '@jcstdio/jc-utils'
 * 
 * const ENV_DIR = path.join(__dirname, "envs");
 * declare interface ViteEnv = {
 *   VITE_PORT: number;
 * }
 * 
 * export default defineConfig(({ command, mode }) => {
 *   const env = loadEnv(mode, ENV_DIR, "");
 *   const VITE_ENVS:ViteEnv = getViteEnvs<ViteEnv>(env,[
 *     {test:/_PORT$/, (env)=>{ return Number(value); }}
 *   ]);
 *   const { VITE_PORT } = viteEnv;
 *   return {
 *     // vite configs
 *   }
 * })
 * ``` 
 */
function getViteEnvs<T>( envConf: Recordable, filters:filter[]=[]): T {
  const res: any = {};
  for (const envName of Object.keys(envConf)) {
    // 筛选所有以 VITE 开头的 环境变量
    if(/^VITE_/.test(envName)){
      let value = envConf[envName].replace(/\\n/g, '\n');
      // 处理布尔值
      if(value === 'true'){
        value=true
      }else if(value === 'false'){
        value = false
      }

      // 处理应该为数字类型的 VITE_KEY1
      // else if (envName === 'VITE_PORT') {
      //   value = Number(value);
      // }

      filters.forEach((item:filter)=>{
        if(isString(item.test)){
          if(envName===item.test){
            res[envName] = item.handle(envName)
          }
        }else if(isRegExp(item.test)){
          if(item.test.test(envName)){
            res[envName] = item.handle(envName)
          }
        }else{
          throw ValueError('function getViteEnvs got wrong params')
        }
      })
      
      // 记录到返回值中
      // res[envName] = value;
      
      if (typeof value === 'string') {
        process.env[envName] = value;
      } else if (typeof value === 'object') {
        process.env[envName] = JSON.stringify(value);
      }
    }
    
  }
  return res;
}

export {
  getViteEnvs
}